/**
 * Created by wanthering on 2017/9/6.
 */
'use strict'
const mongoose = require('mongoose');
const Audio = mongoose.model('Audio');
const Lesson = mongoose.model('Lesson');
const config = require('../../config/config')

exports.design = async function(ctx){
  let _id = ctx.params.id
  let lessonEntity = await Lesson.findOne({_id})
  if(!lessonEntity) {
    ctx.body = '找不到相应的课后练习题'
  }else{
    let {id,title,q1,q2,article,giftName,giftUrl,faceUrl} = lessonEntity
    await ctx.render('lesson',{id,title,faceUrl,_id,q1,q2,article,giftName,giftUrl})
  }
}


exports.lesson = async function(ctx){
  let body = ctx.request.body;
  let _id = body._id;
  let id = body.id;
  let title = body.title;
  let q1 = body.q1;
  let q2 = body.q2;
  let faceUrl = body.faceUrl;
  let article = body.article;
  let giftName = body.giftName;
  let giftUrl = body.giftUrl;
  let deadline = body.deadline;

  console.log(deadline)

  let lessonEntity = await Lesson.findOne({_id})

  if(!lessonEntity){
    lessonEntity = new Lesson({id,deadline,faceUrl,title,q1,q2,article,giftName,giftUrl})
    lessonEntity = await lessonEntity.save()
  }else{
    lessonEntity.q1 = q1;
    lessonEntity.q2 = q2;
    lessonEntity.article = article;
    lessonEntity.giftName = giftName;
    lessonEntity.giftUrl = giftUrl;
    lessonEntity.faceUrl = faceUrl;
    lessonEntity.deadline = deadline;
    lessonEntity = await lessonEntity.save()
    ctx.redirect('/lesson/'+_id)
  }
}


exports.new = async function(ctx){
  let id = ctx.params.id
  let audioEntity = await Audio.findOne({id})
  if(!audioEntity) {
    ctx.body = '找不到相应的资源，无法创建链接'
  }else{
    let {title,faceUrl} = audioEntity
    let lessonEntity = await Lesson.findOne({id})
    if(!lessonEntity){
      lessonEntity = new Lesson({
        id,title,faceUrl
      })
      lessonEntity = await lessonEntity.save()
    }

    ctx.redirect('/lesson/'+lessonEntity._id)
  }
}

exports.mainPage = async function(ctx){
  let _id = ctx.params.id
  console.log(_id)
  let lessonEntity = await Lesson.findOne({_id})
  console.log(lessonEntity)
  if(!lessonEntity){
    ctx.body = '找不到相应的资源'
  }else{
    let {q1,q2,deadline,article,giftUrl,giftName,faceUrl,id,title,_id} = lessonEntity
    await ctx.render('homework',{q1,q2,deadline,article,giftUrl,giftName,faceUrl,id,title,_id})
  }
}